#include <QtGui>
#include <QtXml>
#include "stage3.h"
//
Stage3::Stage3() 
	: Stage()
{
	_tree = 0;
	
}
//
void Stage3::clear()
{
	//qDebug() << Q_FUNC_INFO << _tree;
	//_tree->disconnect();
	if(_tree) _tree->clear();
}
//
void Stage3::setTreeWidget(DragTreeWidget *tv)
{
	_tree = tv;
	_tree->setAcceptCrdOnTopLevel(false);
	_tree->setAttributes(attrModel());
	_tree->setMinimumWidth(200);
	_tree->showMenuDominant(false);
	_tree->showDominant(true);
	connect(_tree,SIGNAL(itemChanged(QTreeWidgetItem*,int)),SLOT(slotItemChanged(QTreeWidgetItem*)));
	connect(_tree,SIGNAL(editItem(QTreeWidgetItem*)),SLOT(slotEditDomen(QTreeWidgetItem*)));

}
//
QTreeWidget *Stage3::tree()
{
	return _tree;
}
// сохранение ветви дерева
void Stage3::saveItem(QDomElement *elem, QTreeWidgetItem *item)
{
	QDomElement newelem;
	QDomDocument doc;
	newelem = doc.createElement("item");
	if(!item->parent()){
		newelem.setAttribute("dalias",item->text(0));
		newelem.setAttribute("name",item->data(0,Qt::UserRole).toString());
	} 
	//else
	//	newelem.setAttribute("uid",item->data(0,Qt::UserRole+1).toString());
	newelem.setAttribute("order",item->data(0,Qt::UserRole).toInt());
	for(int i=0;i<item->childCount();i++){
		saveItem(&newelem,item->child(i));
	}
	elem->appendChild(newelem);
}
//
QDomElement Stage3::xml()
{
	//qDebug() << Q_FUNC_INFO << "start";
	QDomElement node;
	QDomDocument doc;
	node = doc.createElement("stage3");
	//return node;	
	for(int i=0;i<_tree->topLevelItemCount();i++){
		QTreeWidgetItem *item = _tree->topLevelItem(i);
		saveItem(&node,item);		
	}
	
	//qDebug() << Q_FUNC_INFO << "end";
	return node;	
}
//
void Stage3::loadElement(QDomElement *elem,QTreeWidgetItem *pitem)
{
	if(!elem) return;
	QDomElement e = elem->firstChildElement("item");
	while(!e.isNull()){
		Attribute *dl = attribute(e.attribute("order").toInt());
		if(dl){
			QTreeWidgetItem *item = new QTreeWidgetItem(pitem,QStringList() << dl->alias());
			item->setFlags(item->flags() | Qt::ItemIsDropEnabled);
			item->setData(0,Qt::UserRole,dl->order());
			//item->setData(0,Qt::UserRole+1,e.attribute("uid"));
			if(item->data(0,Qt::UserRole+1)==1)
				item->setForeground(0,QBrush(Qt::red));
			if(pitem->parent()==NULL && pitem->child(0)==item){
				_tree->setDominant(item);
			}
			emit treeUpdated(dl->order());
			loadElement(&e,item);
			item->setExpanded(true);
		}
		e = e.nextSiblingElement("item");
	}
	
}
//
bool Stage3::load(QDomElement elem)
{
	if(elem.isNull()) return false;
	QDomElement e = elem.firstChildElement("item");
	while(!e.isNull()){
		QTreeWidgetItem *item = new QTreeWidgetItem(_tree,QStringList() << e.attribute("dalias"));
		item->setFlags(item->flags() | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
		item->setData(0,Qt::UserRole,e.attribute("name"));
	    item->setFont(0,QFont("Times", 10, QFont::Bold));
		
		loadElement(&e,item);
		_tree->expandItem(item);
		e = e.nextSiblingElement("item");
	}
	return true;
}
//
bool Stage3::useDomain(QTreeWidgetItem *item,int order)
{
	if(!item) return false;
	bool used = false;
	if(item->data(0,Qt::UserRole)==order) return true;
	for(int i=0;i<item->childCount();i++){
		used = useDomain(item->child(i),order);
		if(used) break;
	}
	
	return used;
}
//
Attribute *Stage3::useDomain(int order)
{
//	qDebug("useDomain(int)");
	bool used=false;
	for(int i=0;i<_tree->topLevelItemCount();i++){
		QTreeWidgetItem *item = _tree->topLevelItem(i);
		used = useDomain(item,order);		
		if(used) break;		
	}
	
	if(used) return attribute(order);
	else return 0;
}
//
void Stage3::slotItemChanged(QTreeWidgetItem *)
{	
//	qDebug() << "slotItemChagned fired";
	emit treeUpdated();
}
//
void Stage3::slotAttrChanged(int oldnom,Attribute *label)
{
	//     ()
	QTreeWidgetItem *item,*child;
	bool changed = false;
	for(int i=0;i<_tree->topLevelItemCount();i++){
		item = _tree->topLevelItem(i);
		for(int j=0;j<item->childCount();j++){
			child = item->child(j);
			changed = changeAttribute(oldnom,label,child);
			if(changed) break;
		}
		if(changed) break;
	}		
}
//
void Stage3::slotEditDomen(QTreeWidgetItem*item)
{

}
//
void Stage3::attributesToServerFormat(QDomElement *elem,QTreeWidgetItem *pitem)
{
	if(!elem) return;
	QTreeWidgetItem *item;
	Attribute *attr;
	for(int i=0;i<pitem->childCount();i++){
		item = pitem->child(i);
		attr = attribute(item->data(0,Qt::UserRole).toInt());
		if(attr){
			QDomElement eAttr = attr->serverFormat();
			attributesToServerFormat(&eAttr,item);
			elem->appendChild(eAttr);	
		}
	}
}

//
/*
QDomElement Stage3::serverFormat()
{
	QDomElement node;
	QDomDocument doc;
	node = doc.createElement("ums");
	for(int i=0;i<_tree->topLevelItemCount();i++){
		QTreeWidgetItem *item = _tree->topLevelItem(i);
		
		QDomElement domen = doc.createElement("domain");
		domen.setAttribute("name",item->data(0,Qt::UserRole).toString());
		QDomElement elem = doc.createElement("dalias");
		QDomText text = doc.createTextNode(item->text(0));
		elem.appendChild(text);
		domen.appendChild(elem);
		attributesToServerFormat(&domen,item);
		node.appendChild(domen);
	}	
	return node;
}*/
/** возвращает xml серверного формата
\param name физическое наименование БД
\param alias логическое наименование БД
*/
QDomElement Stage3::serverFormat(QString name,QString alias)
{
	QDomElement node;
	QDomDocument doc;
	node = doc.createElement("ums");
	node.setAttribute("name",name);
	node.setAttribute("alias",alias);
	for(int i=0;i<_tree->topLevelItemCount();i++){
		QTreeWidgetItem *item = _tree->topLevelItem(i);
		
		QDomElement domen = doc.createElement("domain");
		domen.setAttribute("name",item->data(0,Qt::UserRole).toString());
		domen.setAttribute("dalias",item->text(0));
		attributesToServerFormat(&domen,item);
		node.appendChild(domen);
	}	
	return node;
}

void Stage3::slotEditDomain()
{
	qDebug() << "Stage3::slotEditDomain()";	
	if(_tree->selectedItems().count()==0 || _tree->selectedItems()[0]->parent()!=0) return;
	slotEditDomen(_tree->selectedItems()[0]);
}


void Stage3::slotRemoveDomain()
{
	qDebug() << "Stage3::slotRemoveDomain()";	
	if(_tree->selectedItems().count()==0 || _tree->selectedItems()[0]->parent()!=0) return;
	_tree->takeTopLevelItem(_tree->indexOfTopLevelItem(_tree->selectedItems()[0]));
	
}

/*! возвращает новое имя для куба
*/
QString Stage3::newCubeName()
{
	return QString("gipercube%1").arg(cubeCount()+1);
}
/*! возвращает количество кубов
*/
int Stage3::cubeCount()
{
	return _tree->topLevelItemCount();	
}

void Stage3::slotAddCube()
{
	QString alias = trUtf8("Гиперкуб");
	QTreeWidgetItem *item = new QTreeWidgetItem(_tree,QStringList()<<alias);
	item->setFlags(item->flags() | Qt::ItemIsEditable);
	item->setFont(0,QFont("Times", 10, QFont::Bold));

	item->setText(0,alias);
	item->setData(0,Qt::UserRole,newCubeName());
}
